@using System.Web.Optimization
@using VocaDb.Model.Domain
@using VocaDb.Model.Domain.Security
@using VocaDb.Model.Domain.Songs
@using VocaDb.Model.Domain.Albums
@using VocaDb.Model.Domain.Images
@using VocaDb.Model.Helpers
@using VocaDb.Web.Helpers;
@using VocaDb.Web.Models;
@using VocaDb.Web.Models.Shared
@using R = ViewRes.Album;
@using Res = ViewRes.Album.DetailsStrings;
@using EntryRes = ViewRes.EntryDetailsStrings;
@inherits VocaDb.Web.Code.VocaDbPage<AlbumDetails>

@{
	ViewBag.Parents = new[] { Html.ActionLink(ViewRes.SharedStrings.Albums, "Index") };
	var url = PageProperties.CanonicalUrl;
}

@section Head {
	@HtmlHelpers.OpenGraphMetaTags(PageProperties)
	<link rel="canonical" href="@url" />
	@Styles.Render("~/Scripts/jqwidgets27/styles/css")
}

@section Toolbar {

	<a href="#" id="addAlbumLink" class="@(Login.Manager.IsLoggedIn ? "" : "disabled")" style="@(Model.UserHasAlbum ? "display: none;" : "")">@ViewRes.Album.DetailsStrings.AddToCollection</a>
	<a href="#" id="updateAlbumLink" class="@(Login.Manager.IsLoggedIn ? "" : "disabled")" style="@(Model.UserHasAlbum ? "" : "display: none;")">@ViewRes.Album.DetailsStrings.UpdateCollection</a>

	@Html.ActionLink(ViewRes.SharedStrings.Edit, "Edit", new { id = Model.Id }, new { id = "editAlbumLink", @class = (Model.CanEdit ? "" : "disabled") })

	@Html.ActionLink(ViewRes.EntryDetailsStrings.ViewModifications, "Versions", new { id = Model.Id }, new { id = "viewVersions" })

	<span>
		@Html.ActionLink(ViewRes.Album.DetailsStrings.DownloadTrackList, "DownloadTags", new { id = Model.Id }, new { id = "downloadTags" })
		<a data-bind="click: downloadTagsDialog.show" href="#" id="downloadTagsCustom">@R.DetailsStrings.Customize</a>
	</span>

	<a href="#" id="reportEntryLink" data-bind="click: reportViewModel.show">@ViewRes.EntryDetailsStrings.ReportAnError</a>

	@Helpers.EntryStatusMessage(Model.Status)
}

@if (Model.Deleted) {
	@EntryDetailsHelpers.DeletedBanner(Model.MergedTo)
}

@if (Model.Draft && !Model.Deleted) {
	@Helpers.DraftMessage("glalbums")
}

<div id="tabs" itemscope itemtype="http://schema.org/MusicAlbum" class="js-cloak" data-bind="show">

	<ul>
		<li><a href="#basicInfoTab">@ViewRes.EntryDetailsStrings.BasicInfoTab</a></li>
		<li data-tab="Discussion">
			<a href="#discussionTab">@ViewRes.EntryDetailsStrings.DiscussionTab (@Model.CommentCount)</a>
		</li>
		<li data-tab="Reviews">
			<a href="#reviewsTab">@ViewRes.Album.DetailsStrings.ReviewsTab (@Model.ReviewCount)</a>
		</li>
		<li><a href="#picturesTab">@ViewRes.EntryDetailsStrings.PicturesTab (@(Model.Pictures.Length + 1))</a></li>
		<li><a href="@Url.Action("Related", "Album", new { id = Model.Id })">@R.DetailsStrings.RelatedAlbums</a></li>
		<li><a href="#shareTab">@R.DetailsStrings.Share</a></li>
	</ul>

	<div id="basicInfoTab">
		
		<div class="clearfix">
			<!-- Album cover picture -->
			<div class="pull-left">
				<div id="picCarousel" class="carousel slide">
					<div class="carousel-inner">
						<div class="active item thumbItem">
							@AlbumHelpers.CoverLink(Model)
						</div>
						@foreach (var pic in Model.Pictures) {
							<div class="item thumbItem" itemprop="image">
								@Helpers.EntryPictureFileLink(pic)
								@if (!string.IsNullOrEmpty(pic.Name)) {
									<div class="carousel-caption">
										<h4>@pic.Name</h4>
									</div>
								}
							</div>
						}
					</div>
					@if (Model.Pictures.Any()) {
						<a class="carousel-control left" href="#picCarousel" data-slide="prev">&lsaquo;</a>
						<a class="carousel-control right" href="#picCarousel" data-slide="next">&rsaquo;</a>
					}
				</div>

				@if (Model.RatingCount > 0) {
					<div itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating">
						<meta itemprop="ratingValue" content="@DecimalDot(Model.RatingAverage)" />
						@Helpers.StarsMeta(Model.RatingAverage, 5)<br />
						(<span itemprop="ratingCount">@Model.RatingCount</span> @Res.Ratings)
					</div>
				}			
			</div>

			<table class="properties">
				<tr>
					<td class="entry-field-label-col">@ViewRes.SharedStrings.Name</td>
					<td itemprop="name">
						@Model.Name<br />
						<span class="extraInfo">@Model.AdditionalNames</span>
					</td>
				</tr>

				@if (Model.Vocalists.Any()) {
					<tr>
						<td>@Res.Vocalists</td>
						<td class="artistList">
							@ArtistHelpers.ArtistList(Model.Vocalists, showType: true)
						</td>
					</tr>
				}
				
				@if (Model.Subject != null && Model.Subject.Any()) {
					<tr>
						<td>@EntryRes.Subject</td>
						<td class="artistList">
							@ArtistHelpers.ArtistList(Model.Subject, showRoles: false)
						</td>
					</tr>
				}			

				@if (Model.Producers.Any()) {
					<tr>
						<td>@Res.Producers</td>
						<td class="artistList">
							@ArtistHelpers.ArtistList(Model.Producers, showRoles: Model.ShowProducerRoles)
						</td>
					</tr>
				}
				
				@if (Model.Illustrators != null && Model.Illustrators.Any()) {
					<tr>
						<td>@Res.Illustrators</td>
						<td class="artistList">
							@ArtistHelpers.ArtistList(Model.Illustrators, showRoles: false)
						</td>
					</tr>
				}

				@if (Model.Bands.Any()) {
					<tr>
						<td>@Res.Band</td>
						<td class="artistList">
							@ArtistHelpers.ArtistList(Model.Bands)
						</td>
					</tr>
				}

				@if (Model.Circles.Any()) {
					<tr>
						<td>@Res.Circle</td>
						<td class="artistList">
							@ArtistHelpers.ArtistList(Model.Circles)
						</td>
					</tr>
				}

				@if (Model.Labels.Any()) {
					<tr>
						<td>@Res.Labels</td>
						<td class="artistList">
							@ArtistHelpers.ArtistList(Model.Labels)
						</td>
					</tr>
				}

				@if (Model.OtherArtists.Any()) {
					<tr>
						<td>@Res.OtherArtists</td>
						<td class="artistList">
							@ArtistHelpers.ArtistList(Model.OtherArtists, true)
						</td>
					</tr>
				}

				@if (!Model.Description.IsEmpty) {
					<tr>
						<td>@ViewRes.SharedStrings.Description</td>
						<td class="entry-description" data-bind="with: description">
							@{ Html.RenderPartial("Partials/_EnglishTranslatedString", new EnglishTranslatedStringViewModel(Model.Description)); }
						</td>
					</tr>
				}

				<tr>
					<td>@ViewRes.SharedStrings.Type</td>
					<td>
						@Html.ActionLink(Translate.DiscTypeName(Model.DiscType), "Index", new { discType = Model.DiscType })<br />
					</td>
				</tr>

				<tr>
					<td>@ViewRes.SharedStrings.Tags</td>
					<td>
						<div data-bind="with: tagUsages" class="entry-tag-usages">
							@{ Html.RenderPartial("Partials/_TagList"); }
						</div>
						<a data-bind="jqButton: { disabled: @ToJS(!Login.CanEditTags), icon: 'ui-icon-tag' }, click: tagsEditViewModel.show" href="#">@ViewRes.EntryDetailsStrings.EditTags</a>
						@if (Model.CanRemoveTagUsages) {
							@Html.ActionLink(ViewRes.EntryDetailsStrings.ManageTags, "ManageTagUsages", new { id = Model.Id }, new { id = "manageTags" })
						}
					</td>
				</tr>

				@if (Model.ReleaseDate != null && !Model.ReleaseDate.IsEmpty) {
					<tr>
						<td>@Res.ReleaseDate</td>
						<td>
							@Model.ReleaseDate.Formatted
							@if (Model.ReleaseDateIsInThePast) {
								<small class="muted">@Res.ReleaseDateIsInThePast</small>
							}
							@if (Model.ReleaseDateIsInTheNearFuture) {
								<small class="muted">@Res.ReleaseDateIsInTheNearFuture</small>
							}
							@if (Model.ReleaseDateIsInTheFarFuture) {
								<small class="muted">@Res.ReleaseDateIsInTheFarFuture</small>
							}
							<br />
						</td>
					</tr>
				}

				@if (!string.IsNullOrEmpty(Model.CatNum)) {
					<tr>
						<td>@Res.CatalogNumber</td>
						<td>
							@Model.CatNum<br />
						</td>
					</tr>
				}

				@if (Model.ReleaseEvent != null) {
					<tr>
						<td>@Res.ReleaseEvent</td>
						<td>
							<a href="@Url.Action("Details", "Event", new { id = Model.ReleaseEvent.Id, slug = Model.ReleaseEvent.UrlSlug })" data-bind="eventToolTip: @Model.ReleaseEvent.Id">@Model.ReleaseEvent.Name</a>
						</td>
					</tr>
				}

				@if (Model.PVs.Any()) {
					<tr>
						<td>@Res.PVs</td>
						<td>
							@foreach (var pv in Model.PVs) {
								@Helpers.FormatPVLink(pv, false)<br />
							}
						</td>
					</tr>
				}

				@EntryDetailsHelpers.ExternalLinksRows(Model.WebLinks)

				<tr>
					<td>@ViewRes.EntryDetailsStrings.Stats</td>
					<td>
						<a href="#" id="statsLink" data-bind="click: getUsers">
							@string.Format(ViewRes.EntryDetailsStrings.Hits, Model.Hits).
							@string.Format(R.DetailsStrings.OwnedBy, Model.OwnedBy). @string.Format(R.DetailsStrings.WishlistedBy, Model.WishlistedBy).
						</a>
					</td>
				</tr>

				<tr>
					<td>@ViewRes.EntryDetailsStrings.AdditionDate</td>
					<td>
						@Helpers.UniversalTimeLabel(Model.CreateDate)
					</td>
				</tr>
			</table>
		</div>
		
		@if (Model.Discs.Any() || Model.ContentFocus != ContentFocus.Illustration) {
		<h3>
			@Res.Tracklist
			@if (Model.TotalLength != TimeSpan.Zero) {
				<small>(@string.Format(Res.TotalLength, DateTimeHelper.FormatMinSec(Model.TotalLength)))</small>
			}
		</h3>
			<div class="tracklist">
				@foreach (var disc in Model.Discs) {
					if (Model.Discs.Length > 1) {
						<h4>
							@Res.Disc @disc.DiscNumber
							@if (!string.IsNullOrEmpty(disc.Name)) {
								@:- @disc.Name
							}
							@if (disc.TotalLength != TimeSpan.Zero) {
								<small>(@DateTimeHelper.FormatMinSec(disc.TotalLength))</small>
							}
							@if (disc.IsVideo) {
								<i class="icon-film" title="@Resources.AlbumDiscMediaTypeNames.Video"></i>
							}
						</h4>
					}
					<ul>
						@foreach (var song in disc.Songs) {
							<li class="tracklist-track">
								<div class="tracklist-trackNumber">
									@song.TrackNumber
								</div>
								<div class="tracklist-trackTitle">
									@if (song.Song != null) {
										@SongHelpers.SongLink(song.Song, Model.Id, tooltip: true)
										if (song.Song.LengthSeconds > 0) {
											@(" (" + DateTimeUtils.FormatFromSeconds(song.Song.LengthSeconds) + ")")
										}
										@:&nbsp;
										@Helpers.DraftIcon(song.Song.Status)
										if (song.Song.SongType != SongType.Original && song.Song.SongType != SongType.Unspecified) {
											@SongHelpers.SongTypeLabel(song.Song.SongType)
										}
										@Helpers.PVServiceIcons(song.Song.PVServices)
										@SongHelpers.RatingIcon(song.Rating ?? SongVoteRating.Nothing)
										<br />
										<small class="muted">@song.Song.ArtistString</small>
									} else {
										@song.Name
									}
								</div>
							</li>
						}
					</ul>
				}
			</div>
		}

		@if (!Model.Discs.Any() && Model.ContentFocus != ContentFocus.Illustration) {
			<p>@Res.NoTracklist</p>
		}

		@if (Model.PrimaryPV != null) {
			<div class="song-pv-player">
				@PVHelpers.EmbedPV(Model.PrimaryPV)
			</div>
		}
		
		@if (Model.CanEditPersonalDescription || !string.IsNullOrEmpty(Model.PersonalDescriptionText)) {
			<h3 class="withMargin helpTip" data-bind="qTip: null" title="@EntryRes.PersonalDescriptionHelp">
				@EntryRes.PersonalDescription
			</h3>
			<div class="media" data-bind="with: personalDescription">
				<a data-bind="visible: !author.isEmpty(), attr: { href: vdb.utils.EntryUrlMapper.details('Artist', author.id()) }" class="pull-left">
					<img class="coverPicThumb" alt="Thumb" data-bind="attr: { src: !author.isEmpty() ? author.entry().mainPicture.urlSmallThumb : null }" />
				</a>

				<div class="media-body">
					@if (Model.CanEditPersonalDescription) {
					<div class="pull-right">
						<a data-bind="click: beginEdit" href="#" class="textLink editLink">@ViewRes.SharedStrings.Edit</a>
					</div>
					}
					<h3 class="media-heading" data-bind="visible: !author.isEmpty()">
						<a data-bind="attr: { href: vdb.utils.EntryUrlMapper.details('Artist', author.id()) }, text: author.name"></a>
					</h3>
					<div data-bind="visible: !editing()">
						<p data-bind="markdown: text"></p>
					</div>
					<div data-bind="if: editing()">
						<select data-bind="value: author.id, options: artists, optionsText: 'name', optionsValue: 'id', optionsCaption: '@EntryRes.PersonalDescriptionSelectAuthor'"></select>
						<br />
						<textarea data-bind="textInput: text" rows="5" cols="100" maxlength="2000" class="input-xxlarge"></textarea>
						<br />
						<button type="button" data-bind="click: save" class="btn btn-primary">@ViewRes.SharedStrings.Save</button>
						<button data-bind="click: cancelEdit" class="btn">@ViewRes.SharedStrings.Cancel</button>
					</div>
				</div>
			</div>
		}

		@CommentHelpers.LatestCommentsKnockout()

		<p>
			<a href="#" id="viewCommentsLink">@ViewRes.EntryDetailsStrings.ViewAllComments</a>
		</p>
		
		@if (Model.LatestReview != null) {
			<h3>@Res.LatestReview</h3>

			<div class="media">
				<a class="pull-left" href="@Url.UserDetails(Model.LatestReview.User)">
					@UserHelpers.ProfileIcon(Model.LatestReview.User.MainPicture.UrlThumb, 70)
				</a>

				<div class="media-body">
					<div class="pull-right">
						@HtmlHelpers.LanguageFlag(Model.LatestReview.LanguageCode)
						|
						@VocaDb.Web.Code.TimeAgoStringBuilder.FormatTimeAgo(Model.LatestReview.Date)
					</div>
					<h3 class="media-heading">
						@UserHelpers.UserLink(Model.LatestReview.User)
					</h3>
					
					@if (Model.LatestReviewRatingScore > 0) {
						@Helpers.Stars(Model.LatestReviewRatingScore, 5)
					}

					<div>
						@if (!string.IsNullOrEmpty(Model.LatestReview.Title)) {
							<h4 class="album-review-title">@Model.LatestReview.Title</h4>
						}

						<p>@HtmlHelpers.FormatMarkdown(Model.LatestReview.Text)</p>
					</div>
				</div>
			</div>

			<p class="withMargin">
				<a href="#" id="viewReviewsLink">@string.Format(Res.ViewAllReviews, Model.ReviewCount)</a>
			</p>
		}
			
	</div>

	<div id="discussionTab" data-bind="with: comments">
		@CommentHelpers.EditableComments(UserContext.HasPermission(PermissionToken.CreateComments), well: false)
	</div>
	
	<div id="reviewsTab" data-bind="with: reviewsViewModel">
		@{ Html.RenderPartial("Partials/_AlbumReviews"); }
	</div>

	<div id="picturesTab">

		<ul class="thumbs">
			@Helpers.ThumbItem(Url.Action("CoverPicture", "Album", new { id = Model.Id, v = Model.Version }),
				Url.ImageThumb(Model, ImageSize.Thumb),
				ViewRes.Album.DetailsStrings.CoverPicture)
			@foreach (var pic in Model.Pictures) {
				@Helpers.ThumbItem(Url.EntryPictureFile(pic, ImageSize.Original), Url.EntryPictureFile(pic, ImageSize.Thumb), pic.Name)
			}
		</ul>

	</div>

	<div id="shareTab">
		<div>
			<label>
				@ViewRes.EntryDetailsStrings.Social<br />
				@EntryDetailsHelpers.LargeShareLinks(PageProperties.Title, url)
				<br /><br />
			</label>
		</div>		
		<div>
			@ViewRes.EntryDetailsStrings.Link<br />
			<input type="text" value="@url" class="input-large" onclick="this.select();" />
		</div>
		<div>
			<a href="http://daringfireball.net/projects/markdown/">Markdown</a><br />
			<input type="text" value="@VocaDb.Model.Service.Helpers.MarkdownHelper.CreateMarkdownLink(url, Model.Name)" class="input-xxlarge" onclick="this.select();" />
		</div>
	</div>

</div>

<div data-bind="with: tagsEditViewModel">
	@{ Html.RenderPartial("Partials/_TagsEdit"); }
</div>

<div id="userCollectionsPopup" title="@R.DetailsStrings.AlbumInCollections">

	<div data-bind="html: usersContent"></div>

</div>

@{ Html.RenderPartial("Partials/_DownloadTagsDialog"); }

@AlbumHelpers.EditCollectionDialog(Model.AlbumPurchaseStatus, Model.AlbumMediaType)

@EntryDetailsHelpers.ReportEntryPopupKnockout()

@section BodyScripts {
	@Scripts.Render("~/bundles/Album/Details", "~/bundles/jqxRating")
	<script type="text/javascript">

		$(document).ready(function() {

			moment.locale('@Culture');
			ko.punches.enableAll();

			var urlMapper = new vdb.UrlMapper("@Url.Content("~/")");
			var repoFactory = new vdb.repositories.RepositoryFactory(urlMapper, @LanguagePreferenceInt, @UserContext.LoggedUserId);
			var albumRepo = repoFactory.albumRepository();
			var userRepo = repoFactory.userRepository();
			var artistRepo = repoFactory.artistRepository();

			vdb.resources.album = {
				addedToCollection: @ToJS(AjaxRes.AlbumStrings.AddedToCollection)
				};
			vdb.resources.albumDetails = @Html.Raw(JsonHelpers.Serialize(new { download = AjaxRes.AlbumStrings.Download }));

			var reportTypes = @ToJS(Translate.AlbumReportTypeNames.Select(r => new {
				r.Id,
				r.Name,
				NotesRequired = AlbumReport.ReportTypesWithRequiredNotes.Contains(r.Id)
			}));

			var jsonModel = @Html.Raw(Model.Json);
			var formatString = '@(Login.Manager.IsLoggedIn ? Login.User.AlbumFormatString : "")';
			var canDeleteAllComments = @ToJS(UserContext.HasPermission(PermissionToken.DeleteComments));
			var viewModel = new vdb.viewModels.AlbumDetailsViewModel(albumRepo, userRepo,
				artistRepo,
				jsonModel,
				reportTypes,
				@UserContext.LoggedUserId,
				@LanguagePreferenceInt,
				canDeleteAllComments, formatString, @ToJS(Model.Description.ShowEnglish(UserContext.LanguagePreference)));
			ko.applyBindings(viewModel);

			initAlbumDetailsPage(@Model.Id, @Model.CollectionRating,
				"@ViewRes.SharedStrings.Save", urlMapper, viewModel);

		});

	</script>
}